package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClazzService clazzService;

    /**
     * 分页查询
     * @param param
     * @return
     */
    @Override
    public PageResult<Student> getPageResult(StudentQueryParam param) {
        Page<Student> page = new Page<>(param.getPage(), param.getPageSize());

        //根据最后修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));

        //构建条件查询
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .like(param.getName() != null && !param.getName().isEmpty(), Student::getName, param.getName())
                .eq(param.getDegree() != null, Student::getDegree, param.getDegree())
                .eq(param.getClazzId() != null, Student::getClazzId, param.getClazzId());

        page = page(page, queryWrapper);

        //获取班级名称
        List<Clazz> clazzs = clazzService.list();
        Map<Long,String> clazzMap = clazzs.stream()
                .collect(Collectors.toMap(Clazz::getId, Clazz::getName));
        List<Student> students = page.getRecords().stream()
                .peek(student -> student.setClazzName(clazzMap.get(student.getClazzId())))
                .toList();

        PageResult<Student> pageResult = new PageResult<>(page.getTotal(),students);
        return pageResult;
    }

    @Override
    public void deductScore(Long id, Integer score) {
        Student student = getById(id);
        student.setViolationCount(student.getViolationCount() + 1);
        student.setViolationScore(student.getViolationScore() + score);
        updateById( student);

    }

}
